<template>
  <div class="store-collection-item"
       id="collectionStore">
    <Row>
      <Col :xs="5"
           :sm="5"
           :md="5"
           :lg="5"
           class="Col_left">
      <Tree :data="data2"
            show-checkbox
            :multiple="false"
            @on-select-change="check"
            @on-check-change="clickCheck"
            @on-toggle-expand="expand_change"></Tree>
      </Col>
      <Col :xs="19"
           :sm="19"
           :md="19"
           :lg="19"
           class="Col_right">
      <div class="Col_right_list">
        <div style="margin-bottom:24px;text-align: right;padding:30px 30px 0 0">
          <Button type="primary"
                  @click="add"
                  style="width:80px"
                  v-if="showbtn">添加</Button>
        </div>
        <Table :columns="columns7"
               class="table-list"
               :height="this.tableHeight"
               :data="data6"
               v-if="showtable">
          <template slot-scope="{ row }"
                    slot="productType">
            <span>{{ row.productType }}</span>
          </template>
          <template slot-scope="{ row }"
                    slot="productDesc">
            <p class='collection-productdesc'>{{ row.productDesc }}</p>
          </template>
          <template slot-scope="{ row,index }"
                    slot="action">
            <Icon class="iconsys iconedit"
                  @click="uptShow(row,index)"
                  title="编辑" />
            <Poptip confirm
                    style="text-align:left"
                    title="你确定要删除吗？"
                    @on-ok="remove(row,index)"
                    class="poptip_del"
                    @on-cancel="cancel">
              <Icon class="iconsys icondel"
                    size="17"
                    title="删除" />
            </Poptip>
          </template>
        </Table>
        <!-- <div class="content_page" v-if="showtable">
                  <span>共计100条</span>
                  <Page :total="50"  @on-change="pageNum" class-name="page" show-sizer/>
              </div> -->
      </div>
      <div class="Col_right_detail"
           v-if="showdetail">
        <p>
          <span>商品详情</span>
          <Button type="default"
                  style="width:80px"
                  @click="upt">修改</Button>
        </p>
        <ul>
          <li>
            <span style="margin-right:25px">名称:</span>
            <span>{{productDetails.productName}}</span>
          </li>
          <li>
            <span style="margin-right:25px">类型:</span>
            <span>{{productDetails.productType}}</span>
          </li>
          <li>
            <span style="margin-right:25px">单价:</span>
            <span>{{productDetails.productPrice}} 元</span>
          </li>
          <li>
            <span style="margin-right:25px">打印小票:</span>
            <span>{{parseInt(productDetails.printVoucher) === 1 ? '是':'否'}}</span>
          </li>
          <li style="display:flex">
            <span style="margin-right:25px">说明:</span>
            <p style="width:462px"
               class="store-collection-detail">{{productDetails.productDesc}}</p>
          </li>
        </ul>
      </div>
      </Col>
    </Row>
    <Drawer :title="title"
            :closable="false"
            v-model="value1"
            id="collectionStoreDrawer"
            width="540">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            v-if="true">
        <FormItem label="类型"
                  prop="type">
          <Select v-model="formValidate.type"
                  placeholder="请选择"
                  class="box_input"
                  :disabled="selecteddisabled"
                  @on-change="Select_change">
            <Option value='0'>游戏卡</Option>
            <Option value='2'>休闲项目</Option>
            <Option value='3'>商品</Option>
            <Option value='13'>手工售币</Option>
          </Select>
        </FormItem>
        <FormItem label="商品名称"
                  prop="name">
          <Input v-model="formValidate.name"
                 placeholder="最多可输入14字"
                 :maxlength="14"
                 class="box_input"
                 @on-keyup="filterSpace"></Input>
        </FormItem>
        <FormItem label="单价"
                  prop="price">
          <!-- <InputNumber v-model="formValidate.price" placeholder="请输入单价" :max="9999.99" :step="1" :min="0.99"  class="box_input" @on-blur='onBlur'></InputNumber> -->
          <Input class="box_input"
                 placeholder="输入范围为0.00 ~ 9999.99"
                 v-model="formValidate.price"
                 @on-keyup='keyUp'
                 @on-blur="priceBlur"
                 :maxlength="7"></Input>
          <span style="margin-left:10px">元</span>
        </FormItem>
        <FormItem label="打印小票"
                  prop="printVoucher">
          <RadioGroup v-model="formValidate.printVoucher">
            <Radio label="1"
                   style="margin-left:35px">是</Radio>
            <Radio label="0"
                   style="margin-left:35px">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="说明"
                  prop="desc">
          <Input v-model="formValidate.desc"
                 type="textarea"
                 :autosize="{minRows: 4,maxRows: 6}"
                 :maxlength="300"
                 placeholder="添加说明..."
                 class="box_input"></Input>
          <span class="rol_tipsd"
                style="padding-right:130px;">{{formValidate.desc?formValidate.desc.length:0}}/300</span>
        </FormItem>
      </Form>
      <div class="demo-drawer-footer">
        <Button @click="handleReset('formValidate')"
                style="margin-right:20px;width:72px">取消</Button>
        <Button type="primary"
                @click="handleSubmit('formValidate')"
                style="width:72px">保存</Button>
      </div>
    </Drawer>
  </div>
</template>
<script>
import { getbusinessItemQuery, getproductQuery, setproductDelete, setproductSave, setbizitemUpdate } from '@/api/setting'
export default {
  data () {
    // const validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('单价不能为空'))
    //   } else if (Number(value) < 0.00 || Number(value) > 9999.99) {
    //     callback(new Error('输入范围为0.00 ~ 9999.99'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      title: '',
      tableHeight: 0,
      value1: false,
      isDelete: true,
      showbtn: false,
      showdetail: false,
      selecteddisabled: false,
      showtable: true,
      list: ['游戏卡', '', '休闲项目', '商品', '', '', '', '', '', '', '', '', '', '手工售币'],
      businessid: '',
      productId: '',
      state: '',
      productDetails: {
        productName: '',
        productType: '',
        productPrice: null,
        printVoucher: '',
        productDesc: ''
      },
      data2: [
      ],
      formValidate: {
        name: '',
        type: '',
        price: '',
        printVoucher: '0',
        desc: ''
      },
      ruleValidate: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'change' }
        ],
        price: [
          { required: true, type: 'string', message: '单价不能为空', trigger: 'blur' }, { required: true, message: '输入范围为0.00到9999.99之间', trigger: 'blur', pattern: /^\d{1,4}(\.\d{1,2})?$/ }
        ],
        printVoucher: [
          { required: true, message: '打印小票不能为空', trigger: 'change' }
        ],
        desc: [
          // { required: true, message: '请添加说明', trigger: 'blur' },
          // { type: 'string', max: 20, message: 'Introduce no less than 20 words', trigger: 'blur' }
        ]
      },
      columns7: [
        {
          title: '商品名称',
          key: 'productName',
          width: 230
        },
        {
          title: '类型',
          slot: 'productType',
          align: 'center'
          // width: 100
        },
        {
          title: '单价',
          key: 'productPrice',
          align: 'center',
          width: 100
        },
        {
          title: '说明',
          slot: 'productDesc',
          align: 'center'
          // width: 350
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          slot: 'action'
        }
      ],
      data6: [
      ]
    }
  },
  computed: {
  },
  created () {
  },
  mounted () {
    this.getleftTree()
    if (!this.hasPermission('moms:setting:bizitem')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    keyUp (e) {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formValidate.price !== '' && this.formValidate.price.substring(0, 1) === '.') {
        this.formValidate.price = ''
      }
      this.formValidate.price = this.formValidate.price.replace(/[^\d.]/g, '')
      this.formValidate.price = this.formValidate.price.replace(/\.{2,}/g, '.')
      this.formValidate.price = this.formValidate.price.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formValidate.price = this.formValidate.price.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      if (this.formValidate.price.indexOf('.') < 0 && this.formValidate.price !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formValidate.price.substring(0, 1) === '0' && this.formValidate.price.length === 2) {
          this.formValidate.price = this.formValidate.price.substring(1, this.formValidate.price.length)
        }
      }
      if (this.formValidate.price > 9999.99) {
        this.formValidate.price = this.formValidate.price.substring(0, 4)
      }
    },
    priceBlur () {
      this.formValidate.price = this.formValidate.price + ''
      this.formValidate.price = this.formValidate.price.replace(/[^\d.]/g, '')
      if (this.formValidate.price === '') {
        this.formValidate.price = ''
      } else if (this.formValidate.price.indexOf('.') === -1) {
        this.formValidate.price = this.formValidate.price + '.00'
      } else if (this.formValidate.price.indexOf('.')) {
        let ste = this.formValidate.price.substring(this.formValidate.price.indexOf('.') + 1)
        if (!ste) {
          this.formValidate.price = this.formValidate.price + '00'
        }
        if (ste.length === 1) {
          this.formValidate.price = this.formValidate.price + '0'
        } if (ste.length > 2) {
          this.formValidate.price = this.formValidate.price.substring(0, this.formValidate.price.indexOf('.') + 3)
        }
      }
    },
    onBlur () {
      let dot = /\./
      if (dot.test(this.formValidate.price)) {
        let update = String(this.formValidate.price).split('.')[0] + '.' + String(this.formValidate.price).split('.')[1].substring(0, 2)
        this.formValidate.price = Number(update)
      }
    },
    filterSpace () {
      this.formValidate.name = this.formValidate.name.replace(/\s+/g, '')
    },
    expand_change (e) { // 父树节点展开关闭
      this.businessid = e.businessItemId
    },
    Select_change (value) {
      this.formValidate.type = value
    },
    add () {
      this.title = '添加收款项'
      this.productDetails.productId = null
      this.selecteddisabled = false
      this.value1 = true
      this.formValidate.name = ''
      this.formValidate.type = ''
      this.formValidate.printVoucher = '0'
      this.formValidate.price = ''
      this.formValidate.desc = ''
      if (this.$refs.formValidate) {
        this.$refs.formValidate.resetFields()
      }
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) { // 验证保存
          if (this.productDetails.productId) {
            setproductSave({ // 编辑的保存
              'productId': this.productDetails.productId,
              'productName': this.formValidate.name,
              'productPrice': this.formValidate.price,
              'businessItem': this.businessid,
              'productDesc': this.formValidate.desc,
              'printVoucher': this.formValidate.printVoucher,
              'priceType': '0',
              'productType': parseInt(this.formValidate.type),
              'shopId': this.$route.query.id,
              'merchantId': this.$store.state.user.merchantId
            }).then((res) => {
              if (res.data.status === 200) { // 成功后继续调用 列表接口
                this.$Message.success('修改成功！')
                this.value1 = false
                this.productDetails.productName = res.data.data.productName
                this.productDetails.productType = this.list[res.data.data.productType]
                this.productDetails.productPrice = res.data.data.productPrice
                this.productDetails.printVoucher = res.data.data.printVoucher + ''
                this.productDetails.productDesc = res.data.data.productDesc
                getproductQuery({ // 获取子级商品列表
                  'businessItem': this.businessid,
                  'shopId': this.$route.query.id
                }).then((res) => {
                  if (res.data.status === 200) {
                    res.data.data.forEach((item) => {
                      item.productType = this.list[item.productType]
                    })
                    this.data6 = res.data.data
                  } else {
                    this.$Message.error(`${res.data.error}`)
                    // res.data.data.forEach((item) => {
                    //   item.productType = this.list[item.productType]
                    // })
                    // this.data6 = res.data.data
                  }
                })
                this.getleftTree()// 然后请求一下树结构
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          } else {
            setproductSave({ // 新增的保存
              'productId': null,
              'productName': this.formValidate.name,
              'productPrice': this.formValidate.price,
              'businessItem': this.businessid,
              'productDesc': this.formValidate.desc,
              'printVoucher': this.formValidate.printVoucher,
              'priceType': '0',
              'productType': parseInt(this.formValidate.type),
              'shopId': this.$route.query.id,
              'merchantId': this.$store.state.user.merchantId
            }).then((res) => {
              if (res.data.status === 200) { // 成功后继续调用 列表接口
                this.$Message.success('新增成功！')
                this.value1 = false
                getproductQuery({ // 获取子级商品列表
                  'businessItem': this.businessid,
                  'shopId': this.$route.query.id
                }).then((res) => {
                  res.data.data.map((item) => {
                    item.productType = this.list[item.productType]
                  })
                  this.data6 = res.data.data
                })
                this.getleftTree()// 然后请求一下树结构
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }
        } else {
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
      this.value1 = false
      this.showupt = true
    },
    uptShow (row) { // 编辑
      if (this.$refs.formValidate) {
        this.$refs.formValidate.resetFields()
      }
      this.selecteddisabled = true
      this.title = '编辑收款项'
      this.productDetails.productId = row.productId
      this.value1 = true
      this.formValidate.name = row.productName
      this.formValidate.type = row.productType ? (this.list.indexOf(row.productType) === 1 ? '' : (this.list.indexOf(row.productType) + '')) : ''
      this.formValidate.printVoucher = row.printVoucher === null ? '' : (row.printVoucher + '')
      this.formValidate.price = row.productPrice + ''
      this.formValidate.desc = row.productDesc
    },
    upt () { // 修改
      if (this.$refs.formValidate) {
        this.$refs.formValidate.resetFields()
      }
      this.selecteddisabled = true
      this.formValidate.name = this.productDetails.productName
      this.formValidate.type = this.productDetails.productType ? (this.list.indexOf(this.productDetails.productType) === 1 ? '' : (this.list.indexOf(this.productDetails.productType) + '')) : ''
      this.formValidate.printVoucher = this.productDetails.printVoucher === null ? '' : (this.productDetails.printVoucher + '')
      this.formValidate.price = this.productDetails.productPrice
      this.formValidate.desc = this.productDetails.productDesc
      this.value1 = true
    },
    getleftTree () { // 页面加载请求树结构
      getbusinessItemQuery({ // 获取左边树结构
        'shopId': this.$route.query.id,
        'productShow': '1',
        'merchantId': this.$store.state.user.merchantId
      }).then((res) => {
        if (res.data.status === 200) {
          let Tree_list = res.data.data
          let list = []
          for (let i = 0; i < Tree_list.length; i++) {
            let obj = {}
            if (Tree_list[i].useFlag === 1) {
              obj.checked = true
            } else {
              obj.checked = false
            }
            obj.title = Tree_list[i].businessItemName
            obj.businessItemId = Tree_list[i].businessItemId
            obj.expand = false
            obj.selected = false
            let list1 = []
            let childrenList = Tree_list[i].productList
            if (childrenList) {
              for (let k = 0; k < childrenList.length; k++) {
                let obj1 = {}
                obj1.productId = childrenList[k].productId // 商品id
                obj1.title = childrenList[k].productName // 商品name
                obj1.productDesc = childrenList[k].productDesc // 商品说明
                obj1.productType = childrenList[k].productType // 商品类型
                obj1.productPrice = childrenList[k].productPrice // 商品价格
                obj1.printVoucher = childrenList[k].printVoucher // 打印小票
                obj1.expand = false
                list1.push(obj1)
              }
            }
            obj.children = list1
            list.push(obj)
          }
          this.data2 = list
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    show (params) {
      this.value1 = true
      this.formValidate.name = params.row.name
      this.formValidate.type = 'a'
      this.formValidate.price = params.row.price
      this.formValidate.desc = params.row.msg
    },
    remove (row, index) { // 删除
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        setTimeout(() => {
          setproductDelete({
            'productId': row.productId
          }).then((res) => {
            this.isDelete = true
            if (res.data.status === 200) {
              this.$Message.success('删除成功')
              this.data6.splice(index, 1)
              this.getleftTree()// 然后请求一下树结构
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    cancel () { // 取消删除的回调
    },
    pageNum () {
    },
    check (a, b) { // 点击节点触发
      if (b.businessItemId) { // 父节点被点击
        this.showbtn = true
        this.showtable = true
        this.showdetail = false
        this.businessid = b.businessItemId // 获取到父级的businessItemId
        getproductQuery({ // 获取子级商品列表
          'businessItem': b.businessItemId,
          // 'productType': '9',
          'shopId': this.$route.query.id
        }).then((res) => {
          if (res.data.status === 200) {
            res.data.data.map((item) => {
              item.productType = this.list[item.productType]
            })
            this.data6 = res.data.data
            if (res.data.data && res.data.data.length >= 13) {
              this.tableHeight = 663
            }
            if (b.selected === false) { // 父节点点击被取消
              this.showbtn = false
              this.data6 = []
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        if (a.length) {
          this.showdetail = true
          this.showtable = false
          this.showbtn = false
          this.productDetails.productId = a[0].productId
          this.productDetails.productName = a[0].title
          this.productDetails.productType = this.list[a[0].productType]
          this.productDetails.printVoucher = a[0].printVoucher + ''
          this.productDetails.productPrice = a[0].productPrice
          this.productDetails.productDesc = a[0].productDesc
        }
      }
    },
    clickCheck (a, b) { // 点击勾选
      if (b.checked) {
        this.state = '1'
      } else {
        this.state = '0'
      }
      setbizitemUpdate({ // 改变状态
        'shopId': this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId,
        'bussinessItemId': b.businessItemId,
        'useFlag': this.state
      }).then((res) => {
        if (res.data.status === 200) {
          if (this.state === '1') {
            this.$Message.success('功能已启用成功')
          } else if (this.state === '0') {
            this.$Message.success('功能已禁用')
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    }
  }
}
</script>
<style lang="less">
.store-collection-item {
  .Col_left {
    height: 749px;
    box-sizing: border-box;
    border-right: 1px solid #e8eaec;
    padding: 20px 0 0 20px;
    overflow: auto;
  }
  .Col_right {
    .content_page {
      height: 80px;
      line-height: 80px;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      .page {
        margin-left: 2%;
      }
    }
    .Col_right_detail {
      width: 598px;
      padding: 30px 0 0 53px;
      p {
        margin-bottom: 70px;
        span {
          color: #17233d;
          font-size: 14px;
          margin-right: 32px;
          font-weight: bold;
        }
      }
      ul {
        color: #464c5b;
        padding-left: 30px;
        li {
          margin-bottom: 15px;
        }
      }
    }
  }
}
</style>
<style lang="less">
.store-collection-item {
  .table-list {
    .collection-productdesc {
      max-height: 38px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }
  ul,
  li {
    padding: 0;
    margin: 0;
    list-style: none;
  }
  .Col_left {
    .ivu-tree li ul .ivu-checkbox-wrapper {
      display: none;
    }
  }
}
#collectionStoreDrawer {
  .box_input {
    width: 280px;
  }
  .demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
}
</style>
